<template>
  <div class="upload-wrap">
    <div v-if="isLook && attaches.length > 0">
      <p :class="['span','span1']">
        <label>{{title}}</label>
      <ul class="flex img-wrap">
        <li v-for="(item,index) in attaches"
            :key="index"
            class="img-item">
          <img :src="item.url"
               alt=""
               class="img"
               @click="previewImage(item)" />
          <nr-img-preview v-if="preview"
                          :src="previewSrc"
                          :on-click="closeImgPreview"
                          :on-keydown="keydownCloseImgPreview" />
          <!-- <div class="file-name">{{item.name}}</div> -->
        </li>
      </ul>
      </p>
    </div>
    <div v-if="!isLook"
         class="upload-box">
      <el-upload v-bind="$attrs"
                 list-type="picture-card"
                 class="upload-ticket-imgs"
                 :class="{ 'hide-upload-btn': fileList.length === this.limit }"
                 action="#"
                 :http-request="uploadFile"
                 :headers="headers"
                 :limit="limit"
                 :file-list="fileList"
                 :before-upload="beforeUpload"
                 :on-preview="handlePictureCardPreview"
                 :on-change="handleEditChange"
                 :on-exceed="handleExceed"
                 :on-remove="handleRemove">
        <i class="el-icon-plus"></i>
        <!-- <div>文件名字</div> -->
        <div slot="file"
             slot-scope="{file}"
             class="img-style">
          <img class="el-upload-list__item-thumbnail"
               :src="file.url"
               alt="">
          <span class="el-upload-list__item-actions">
            <span class="el-upload-list__item-preview"
                  @click="handlePictureCardPreview(file)">
              <i class="el-icon-zoom-in"></i>
            </span>
            <span class="el-upload-list__item-delete"
                  @click="handleRemove(file,fileList)">
              <i class="el-icon-delete"></i>
            </span>
          </span>
        </div>
      </el-upload>
    </div>
    <el-dialog :visible.sync="dialogVisible"
               title="图片"
               append-to-body>
      <img width="100%"
           class="imgsty"
           :src="dialogImageUrl"
           alt="">
    </el-dialog>
  </div>
</template>

<script>
import nrImgPreview from "@/components/nr/imgPreview/Index";
import { uploadCertFile } from "@/api/modules/upload";
export default {
  name: "SealUpload",
  components: { nrImgPreview },
  inheritAttrs: true,
  props: {
    // 上传个数
    limit: {
      type: Number,
      default: 1,
    },
    // 上传类型限制
    type: {
      type: String,
      default: "",
    },
    // 是否是查看
    isLook: {
      type: Boolean,
      default: false,
    },
    // 回显照片
    attaches: {
      type: Array,
      default: () => [],
    },
    title: {
      type: String,
      default: null,
    },
    certType: {
      type: Number,
      default: 1
    },
    position: {
      type: Number, //证书服务上传类型
      default: null
    }
  },
  data () {
    return {
      preview: false,
      fileList: [],
      headers: {
        Authorization: "Bearer " + sessionStorage.getItem("token"),
      },
      dialogImageUrl: "",
      dialogVisible: false,
      uploadPrompt:
        this.type === "file"
          ? "上传文件只能是 pdf、doc、docx、xls、xlsx格式! 单个文件不能超过 3MB!"
          : "上传图片只能是 JPG、JPEG、gif、bmp、PNG 格式! 单个文件不能超过 3MB!",
      file: null,
      previewSrc: "",
    };
  },
  watch: {
    attaches: {
      handler (val) {
        this.fileList = val
      }
    }
  },
  methods: {
    previewImage (item) {
      this.preview = true;
      this.previewSrc = item.url;
    },
    closeImgPreview () {
      this.preview = false;
    },
    handleRemove (file, fileList) {
      this.fileList = fileList.filter((sub) => sub.fileUrl !== file.fileUrl);
      this.$emit("removeFile", file);
    },
    handleEditChange (file, fileList) {
      console.log("handleEditChange", file, fileList)
    },
    handlePreview (file) {
      console.log(file);
    },
    handleExceed () {
      return this.$message.warning(
        `最多可上传${this.limit}个${this.type === "file" ? "文件" : "图片"}`
      );
    },
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 上传文件限制
    beforeUpload (file) {
      if (this.type === "file") {
        return this.fileDoc(file);
      } else if (this.type === "png") {
        return this.picture(file);
      } else {
        this.fileDoc(file);
        this.picture(file);
      }
    },
    uploadFile (file) {
      let form = new FormData();
      // 文件属性
      form.append("file", file.file);
      this.upload(form);
    },
    upload (formData) {
      // 上传图片统一接口
      new Promise((resolve, reject) => {
        uploadCertFile(formData, this.certType).then((response) => {
          let { data } = response;
          resolve(data);
          this.fileList = [{ ...data, position: this.position }];
          this.$emit("uploadSuccess", this.fileList);
        });
      });
    },
    // 上传图片限制
    picture (file) {
      let types = [
        "image/jpeg",
        "image/jpg",
        "image/gif",
        "image/bmp",
        "image/png",
      ];
      const isImage = types.includes(file.type);
      const isLtSize = file.size / 1024 / 1024 < 3;
      if (!isImage) {
        this.$message.error("上传图片只能是 JPG、JPEG、gif、bmp、PNG 格式!");
        return false;
      }
      if (!isLtSize) {
        this.$message.error("上传图片大小不能超过 3MB!");
        return false;
      }
      return true;
    },
    // 上传文件限制
    fileDoc (file) {
      const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);
      const whiteListFile = ["pdf", "doc", "docx", "xls", "xlsx"];
      const isLt3M = file.size / 1024 / 1024 < 3;
      if (whiteListFile.indexOf(fileSuffix) === -1) {
        this.$message.error("上传文件只能是 pdf、doc、docx、xls、xlsx格式!");
        return false;
      }
      if (!isLt3M) {
        this.$message.error("上传文件大小不能超过 3MB!");
        return false;
      }
    },
    keydownCloseImgPreview (e) {
      if (e && e.keyCode == 27) {
        this.preview = false;
      }
    },
  },
};
</script>

<style scoped lang="scss">
.upload-box {
  position: relative;
}
.upload-ticket-imgs {
  position: relative;
  padding-bottom: 5px;
  .upload-wrap {
    display: flex;
    align-items: center;
  }
  &.hide-upload-btn {
    /deep/.el-upload--picture-card {
      display: none;
    }
  }
  .el-upload-list__item-thumbnail {
    height: 100px;
  }
  .img-style {
    position: relative;
  }
}
.upload-ticket-imgs /deep/ .el-upload--picture-card {
  width: 100px;
  height: 100px;
  line-height: 100px;
}
.upload-ticket-imgs /deep/ .el-upload-list--picture-card .el-upload-list__item {
  width: 100px;
  height: 100px;
  line-height: 100px;
}
.file-name {
  width: 100px;
  white-space: pre-wrap;
  word-break: break-all;
}
.span {
  box-sizing: border-box;
  font-size: 14px;
  label {
    display: inline-block;
    margin-right: 10px;
    // min-width: 28%;
    font-size: 14px;
  }
  span {
    font-weight: bold;
  }
  .img-wrap {
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
    list-style: none;
  }
  .img-item {
    .img {
      width: 100px;
      height: 100px;
      background-color: var(--prev-border-color-grey);
    }
    p {
      text-align: center;
    }
  }
}
.span1 {
  width: 100%;
  display: grid;
}
.imgsty {
  height: 75vh !important;
}
/deep/ .el-dialog {
  margin-top: 10vh !important;
}
/deep/ .el-dialog__body {
  padding: 0 20px 20px 20px;
}
</style>
